import Vue from 'vue';
import axios from 'axios';
import components from '@/components';
import App from './App';
import api from './api';
import tools from './utils/tools';
import router from './router';
import store from './store';
import filters from '@/utils/filters';
import packageInfo from '../package.json'; // packageInfo

import { Notify, Button, Area, Empty, Skeleton, Rate, Sku, DropdownMenu, DropdownItem, ActionSheet, Picker, List, Loading, ImagePreview, Sidebar, SidebarItem, PasswordInput, CountDown, NumberKeyboard, Sticky, Cell, Dialog, Popup, Field, CellGroup, Switch, AddressEdit, NavBar, Checkbox, CheckboxGroup, PullRefresh, Swipe, SwipeItem, Image, Lazyload, Stepper, Uploader } from 'vant';
import 'lib-flexible/flexible';
// 全局引入index.css
import './assets/style/index.less'; // 过滤器
import VConsole from 'vconsole';
// 复制到粘贴板插件
import VueClipboard from 'vue-clipboard2';
// 复制到粘贴板插件
VueClipboard.config.autoSetContainer = true;
Vue.use(VueClipboard)
  .use(Button)
  .use(Switch)
  .use(Cell)
  .use(Rate)
  .use(CellGroup)
  .use(Skeleton)
  .use(NavBar)
  .use(Field)
  .use(Loading)
  .use(Sidebar)
  .use(Picker)
  .use(List)
  .use(Empty)
  .use(DropdownMenu)
  .use(DropdownItem)
  .use(SidebarItem)
  .use(Checkbox)
  .use(CheckboxGroup)
  .use(PullRefresh)
  .use(AddressEdit)
  .use(Area)
  .use(PasswordInput)
  .use(NumberKeyboard)
  .use(Popup)
  .use(Dialog)
  .use(ActionSheet)
  .use(Sticky)
  .use(CountDown)
  .use(Swipe)
  .use(SwipeItem)
  .use(Image)
  .use(Lazyload)
  .use(Stepper)
  .use(ImagePreview)
  .use(Sku)
  .use(Uploader);

Vue.prototype.$API = api;
Vue.prototype.$tools = tools;
Vue.config.productionTip = false;
Vue.prototype.$SERVER_URL = process.env.VUE_APP_SERVER_URL;
Vue.prototype.$WEB_URL = process.env.VUE_APP_SERVER_WEB_URL;
// 注册EventBus事件对象
var EventBus = new Vue();
window.EventBus = EventBus;
Object.defineProperties(Vue.prototype, {
  $BUS: {
    get: function () {
      return EventBus;
    }
  }
});

// 注册全局组件
Object.keys(components).forEach(key => {
  const name = components[key].name;
  Vue.component(name, components[key]);
});
Object.keys(filters).forEach(k => Vue.filter(k, filters[k]));

// 版本检查
function checkVersion (to, from, next) {
  // 输出系统当前版本号
  console.info('%c系统当前版本号: ' + packageInfo.version, 'background:#000;color:yellow');
  axios.get(`../static/version.json?_=${Math.random()}`).then((response) => { // 访问前端服务器获取版本号
    if (response.status === 200 && packageInfo.version !== response.data.version) {
      Notify({
        message: '发现新版本，自动更新中...',
        type: 'danger'
      });
      console.info('%c新版本：: ' + response.data.version, 'background:#000;color:yellow');
      setTimeout(() => {
        if (window.api) {
          window.api.sendEvent({
            name: 'reload',
            extra: { type: 'reload' }
          });
        } else {
          location.reload(true);
        }
      }, 1000);
      return;
    }
    ifVersionCorrect(to, from, next);
  }).catch((err) => {
    console.error('checkVersion', err);
    ifVersionCorrect(to, from, next);
  });
}
const whiteList = ['/my', '/cart']; // 不重定向白名单
// 版本检查通过
function ifVersionCorrect (to, from, next) {
  let token = localStorage.getItem('Token');
  if (to.query.isDebug) {
    next();
    return;
  }
  // 判断是否是APP
  if (from.query.isApp) {
    localStorage.setItem('isApp', true);
  }
  if (from.query.isWeb) {
    localStorage.setItem('isWeb', true);
  }
  if (from.query.isDebug) {
    let toQuery = JSON.parse(JSON.stringify(to.query));
    toQuery.isDebug = from.query.isDebug;
    next({
      path: to.path,
      query: toQuery
    });
  }
  if (token) {
    next();
  } else {
    // 页面级授权
    if (whiteList.includes(to.path, 0)) {
      store.dispatch('setLogin', true);
    } else {
      next();
    }
  }
}
router.beforeEach((to, from, next) => {
  // 区分开发环境版本检测
  if (process.env.NODE_ENV === 'production') {
    checkVersion(to, from, next);
  } else {
    ifVersionCorrect(to, from, next);
  }
});
if (tools.getQueryVariable('isDebug')) {
  var vConsole = new VConsole();
  console.log(vConsole);
}
if (tools.getQueryVariable('isApp') && localStorage.getItem('isApp')) {
  window.apiready = function () {
    new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount('#app');
  };
} else {
  new Vue({
    router,
    store,
    render: h => h(App)
  }).$mount('#app');
};
